package org.r.items.tally.consumer.security.userdetails;

import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.r.items.tally.consumer.api.user.TallyUserDetailsRemote;
import org.r.items.tally.consumer.dto.UserInfo;
import org.r.items.tally.consumer.service.UserInfoService;
import org.r.tools.exception.BizException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class TallyUserDetailsService implements UserDetailsService {


    @Resource
    private UserInfoService userInfoService;
    /**
     *  
     * @param username = 登入方式(name、number、email) + 登入账号(username、cellphoneNumber、email)
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        int separatorIndex = username.indexOf(":");
        String loginAway = username.substring(0, separatorIndex);
        String loginAccount = username.substring(separatorIndex + 1);
        UserInfo userInfo;
        if(loginAway.equalsIgnoreCase("name")){
             userInfo = userInfoService.getUserInfoByName(loginAccount);
        }else if(loginAway.equalsIgnoreCase("email")){
            userInfo = userInfoService.getUserInfoByCellPhoneNum(loginAccount);
        }else if(loginAway.equalsIgnoreCase("number")){
            userInfo = userInfoService.getUserInfoByEmail(loginAccount);
        }else{
            throw BizException.error("未知登入方式!");
        }
        if(userInfo == null){
            throw BizException.error("该用户({})信息不存在！", loginAccount);
        }
        return new TallyUserDetails(userInfo);
    }
}
